package site.tuluan.sp4j.common.exception;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import site.tuluan.sp4j.common.core.domain.AjaxResult;
import site.tuluan.sp4j.common.utils.ExceptionUtils;
import site.tuluan.sp4j.common.utils.StringUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

/**
 * 异常返回处理
 *
 * @author tuluan
 */
@RestController
@RequestMapping("${server.error.path:${error.path:/error}}")
public class Sp4jErrorController implements ErrorController {

    @RequestMapping
    public AjaxResult error(HttpServletRequest request) {
        String msg = (String)request.getAttribute(RequestDispatcher.ERROR_MESSAGE);
        if (StringUtils.isEmpty(msg)) {
            msg = ExceptionUtils.getRootExceptionMessage((Exception)request.getAttribute(RequestDispatcher.ERROR_EXCEPTION));
        }

        return AjaxResult.buildFailureResult((int)request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE), msg);
    }
}
